package com.hd.determine.config.mybatis;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.hd.determine.config.properties.DruidProperties;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author chentl
 * @version V1.0
 * @Project 交通运输第三方监测平台
 * @Title MybaitsPlusAutoConfiguration.java
 * @Description mybatis-plus 自动配置
 * @Package com.hd.determine.config
 * @date 2020/12/24 10:10 上午
 * @Copyright: 深圳市宏电技术股份有限公司 All rights reserved.
 */
@Configuration
@ConditionalOnProperty(prefix = "spring.datasource.druid", name = "url")
@MapperScan({"com.hd.determine.modules.**.mapper"})
public class MybaitsPlusAutoConfig {

    @Resource
    private DruidProperties druidProperties;

    /**
     * druid配置
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DruidProperties druidProperties() {
        return new DruidProperties();
    }

    /**
     * mybatis-plus分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        //设置pg方言
        paginationInterceptor.setDialectType(DbType.POSTGRE_SQL.getDb());
        // 开启 count 的 join 优化,只针对部分 left join
//        paginationInterceptor.set(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }

    /**
     * druid数据库连接池
     */
    @Bean(initMethod = "init")
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        druidProperties.config(dataSource);
        return dataSource;
    }

    /**
     * 乐观锁mybatis插件
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

}
